/**
 * Created by hxpeng on 2017/3/24.
 */
(function () {
    'use strict';

    angular.module('App.pages.class.msg')
        .controller('NewAudioMsgCtrl', NewAudioMsgCtrl);

    function NewAudioMsgCtrl($scope,AppUtils,$location,$http,Global,$timeout,MsgModel,$stateParams) {
        var recordingTime,start,end;
        var currentPath = $location.url();

        var vm = this;
        if(AppUtils.isUndefinedOrNull($stateParams.toMemberId)){
            AppUtils.showAlert("请选择宝宝留言");
            AppUtils.goBack();
        }
        vm.recordAuth = false;
        vm.init = function(){
            if(currentPath.indexOf("#") != -1){
                currentPath = currentPath.split('#')[0];
            }
            currentPath = Global.path.wechat_path + currentPath;
            $http.post(Global.path.server_sdk_auth_path,{"url":currentPath})
                .success(function(data){
                    wx.config({
                        debug: false,
                        appId: data.appId,
                        timestamp: data.timestamp,
                        nonceStr: data.noncestr,
                        signature: data.signature,
                        jsApiList: ['startRecord','stopRecord','onVoiceRecordEnd','playVoice','pauseVoice','stopVoice','onVoicePlayEnd','uploadVoice']
                    });
                    wx.ready(function(){
                        wx.startRecord({
                            success: function(){
                                vm.recordAuth = true;
                                wx.stopRecord();
                            },
                            cancel: function () {
                                alert('用户拒绝授权录音');
                            }
                        });
                    });
                    wx.error(function(res){
                        console.log(res);

                    });
                })
                .error(function(data,header,config,status){
                    alert("请求微信sdk校验异常");
                });
        }


        $('#record-btn').on('touchstart', function(event){
            event.preventDefault();
            if(vm.recordAuth){
                $(".spinner").addClass("recording");
                start = new Date().getTime();
                var recordingTime = $timeout(function() {
                    wx.startRecord({
                        success: function(){
                        },
                        cancel: function () {
                            alert('用户拒绝授权录音');
                        }
                    });
                },100);
            }else{
                alert('您已拒绝授权录音了。。');
            }
        });
        //松手结束录音
        $('#record-btn').on('touchend', function(event){
            event.preventDefault();
            $(".spinner").removeClass("recording");
            end = new Date().getTime();
            if((end - start) < 1500){
                end = 0;
                start = 0;
                //小于300ms，不录音
                clearTimeout(recordingTime);
            }else{
                wx.stopRecord({
                    success: function (res) {
                        wx.playVoice({
                            localId: res.localId // 需要播放的音频的本地ID，由stopRecord接口获得
                        });
                        var recordConfirm = AppUtils.showConfirm("确认上传录音吗？");
                        recordConfirm.then(function(result) {
                            if(result) {
                                AppUtils.loading();
                                wx.uploadVoice({
                                    localId: res.localId, // 需要上传的音频的本地ID，由stopRecord接口获得
                                    isShowProgressTips: 0, // 默认为1，显示进度提示
                                    success: function (uploadVoiceRes) {
                                        var obj = {};
                                        obj.mediaId = uploadVoiceRes.serverId;
                                        obj.msgType = 'audio';
                                        obj.toMemberId = $stateParams.toMemberId;
                                        MsgModel.createNewMsg(obj).$promise.then(function(response){
                                            if(response.stat == 'err'){
                                                AppUtils.showAlert(response.msg);
                                            }else{
                                                AppUtils.showTipsTop("上传成功！");
                                            }
                                            AppUtils.loadfinish();
                                        })
                                    }
                                });
                            } else {
                                console.log('You are not sure');
                            }
                        });
                    },
                    fail: function (res) {
                        alert(JSON.stringify(res));
                    }
                });
            }
        });


        $scope.$on('$ionicView.beforeLeave', function(){
            wx.stopRecord();
        });

        vm.init();
    }

})();
